package leetcode.code1356;

import java.util.Arrays;

public class Solution {
	public int[] sortByBits(int[] arr) {
		Integer[] ans = new Integer[arr.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = arr[i];
		}
		Arrays.sort(ans, (a, b) -> {
			int a1 = a, b1 = b;
			int cnt1 = 0;
			while (a > 0) {
				if ((a & 1) == 1) {
					cnt1++;
				}
				a >>>= 1;
			}
			int cnt2 = 0;
			while (b > 0) {
				if ((b & 1) == 1) {
					cnt2++;
				}
				b >>>= 1;
			}
			return cnt1 == cnt2 ? a1 - b1 : cnt1 - cnt2;
		});
		for (int i = 0; i < ans.length; i++) {
			arr[i] = ans[i];
		}
		return arr;
	}
}
